package router

import (
	"crypto/md5"
	"fmt"
	"github.com/gorilla/mux"
	"html/template"
	"io"
	"net/http"
	"os"
	"strconv"
	"time"
)

var CategoryHandlerMap map[string]func(http.ResponseWriter, *http.Request)

func UploadPage(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("static/page/index.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	t.Execute(w, nil)
}

func Upload(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	category := vars["category"]

	CategoryHandlerMap = make(map[string]func(http.ResponseWriter, *http.Request))
	CategoryHandlerMap["image"] = UploadImage
	CategoryHandlerMap["source-map"] = UploadSourceMap
	CategoryHandlerMap["soft"] = UploadSoft

	var handler, err = CategoryHandlerMap[category]
	if !err {
		handler(w, r)
	}
}

// 处理/upload 逻辑
func upload(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method) //获取请求的方法
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("upload.gtpl")
		t.Execute(w, token)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("file")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		fmt.Fprintf(w, "%v", handler.Header)
		f, err := os.OpenFile("./static/image/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) // 此处假设当前目录下已存在upload目录
		if err != nil {
			fmt.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f, file)
	}
}

func UploadImage(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	fileName := vars["file"]
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "Category: %v\n", fileName)
}

func UploadSourceMap(w http.ResponseWriter, r *http.Request) {

}

func UploadSoft(w http.ResponseWriter, r *http.Request) {

}

func Show(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "Category: %v\n", vars["category"])
}

func ShowSourceMap(w http.ResponseWriter, r *http.Request) {

}

func ShowSoft(w http.ResponseWriter, r *http.Request) {

}
